package com.slkj.shilixiaoyuanapp.ui.common.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.entity.contacts.ContactsPeopleEntity;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created  on 2018-08-22
 *
 * @author 唐开阔
 * 所以传递时只传递分组数据
 */
public class ContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public int maxCheckNum;//最大选择数
    /**
     * 点击之前判断，是否会超过maxCheckNum，再进行下一步操作
     */
    public int checkNum;//已选择数
    public ArrayList<ContactsPeopleEntity> mData;
    public Context context;

    public ContactsAdapter(ArrayList<ContactsPeopleEntity> data, Context context,int maxCheckNum) {
        this.mData = data;
        this.context = context;
        this.maxCheckNum = maxCheckNum;
        //获取已经选中的数据
        //展开所有数据
        ArrayList<ContactsPeopleEntity> newData = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
            ContactsPeopleEntity entity = mData.get(i);
            newData.add(entity);
            if ( entity.isExpand()){
                List list = entity.getList();
                newData.addAll(list);
            }
        }
        mData.clear();
        mData.addAll(newData);
        checkNum = ChoseObjActivity.getCheckConstacts(mData).size();

    }

    @Override
    public int getItemViewType(int position) {
        return mData.get(position).getItemType();
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case ContactsPeopleEntity.TYPE_GROUP:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contacts_group, parent, false);
                return new GroupViewHolder(view);
            case ContactsPeopleEntity.TYPE_PEOPLE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contacts_people, parent, false);
                return new PeopleViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            case ContactsPeopleEntity.TYPE_GROUP:
                GroupViewHolder groupViewHolder = (GroupViewHolder) holder;
                groupViewHolder.bind(position, mData.get(position));
                break;
            case ContactsPeopleEntity.TYPE_PEOPLE:
                PeopleViewHolder peopleViewHolder = (PeopleViewHolder) holder;
                peopleViewHolder.bind(position, mData.get(position));
                break;
        }
    }

    class GroupViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.title)
        TextView title;
        @BindView(R.id.tv_num_school)
        TextView num;
        @BindView(R.id.iv)
        ImageView iv;
        @BindView(R.id.img_head)
        ImageView clikeAll;
        View itemView;

        public GroupViewHolder(View View) {
            super(View);
            itemView = View;
            ButterKnife.bind(this, View);
        }

        @SuppressLint("SetTextI18n")
        public void bind(int pos, ContactsPeopleEntity groupEntity) {
            title.setText(groupEntity.getName());
            num.setText("(" + groupEntity.getList().size() + "人)");
            iv.setImageResource(groupEntity.isExpand() ? R.drawable.ic_up : R.drawable.ic_down);

            itemView.setOnClickListener(v -> {
                if (groupEntity.isExpand()) {

                    iv.setImageResource(R.drawable.ic_down);
                    collapse(pos, groupEntity);
                } else {
                    iv.setImageResource(R.drawable.ic_up);
                    expand(pos, groupEntity);
                }

            });
            clikeAll.setImageResource(groupEntity.isCheck() ? R.drawable.ic_checked : R.drawable.ic_un_checked);
            clikeAll.setOnClickListener(v -> {
                int size = groupEntity.getList().size();
                if (groupEntity.isCheck()){
                    checkNum -=  size;
                }else {
                    if (checkNum + size > maxCheckNum){
                        Toast.makeText(context, "最多选择"+maxCheckNum+"个", Toast.LENGTH_SHORT).show();
                        return;
                    }else {
                        checkNum +=  size;
                    }
                }
                groupEntity.setCheck(!groupEntity.isCheck());
                clikeAll.setImageResource(groupEntity.isCheck() ? R.drawable.ic_checked : R.drawable.ic_un_checked);
                for (ContactsPeopleEntity person : groupEntity.getList()) {
                    person.setCheck(groupEntity.isCheck());
                }
                notifyDataSetChanged();
            });
        }
    }

    class PeopleViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_name)
        TextView name;
        @BindView(R.id.img_user)
        ImageView imgUser;
        @BindView(R.id.img_head)
        ImageView imgCheck;
        View itemView;
        public PeopleViewHolder(View view) {
            super(view);
            itemView = view;
            ButterKnife.bind(this, view);
        }
        public void bind(int pos, ContactsPeopleEntity person) {
            name.setText(person.getName());
            Glide.with(context).load(person.getHead()).into(imgUser);
            imgCheck.setImageResource(person.isCheck() ? R.drawable.ic_checked : R.drawable.ic_un_checked);
            itemView.setOnClickListener(v -> {
                if (person.isCheck()){
                    checkNum -= 1;
                }else {
                    if (checkNum + 1 > maxCheckNum){
                        Toast.makeText(context, "最多选择"+maxCheckNum+"个", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    checkNum += 1;

                }
                person.setCheck(!person.isCheck());
                Log.d("tag", ">>>bind---person"+person.hashCode());
                //判断是否全部选中-改变分组的状态
                boolean isParentCheckAll = true;
                ContactsPeopleEntity parent = getParent(pos,person);
                for (ContactsPeopleEntity child :parent.getList()){
                    Log.d("tag", ">>>bind---child"+child.hashCode());

                    if (!child.isCheck()){
                        Log.d("tag", ">>>bind---没选中"  );
                        isParentCheckAll = false;
                        break;
                    }else {
                        Log.d("tag", ">>>bind---选中"  );

                    }
                }
                parent.setCheck(isParentCheckAll);
                notifyDataSetChanged();

            });
        }

    }

    /**
     * 获取所属分组类
     * @param person
     * @return
     */
    private ContactsPeopleEntity getParent(int pos,ContactsPeopleEntity person) {
        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            ContactsPeopleEntity parent =   mData.get(pos - i);
            if (parent.getItemType() == ContactsPeopleEntity.TYPE_GROUP){
                return parent;
            }
        }
        return null;
    }

    /**
     * 展开
     *
     * @param position
     * @return
     */
    public void expand(int position, ContactsPeopleEntity groupEntity) {
        List list = groupEntity.getList();
        mData.addAll(position + 1, list);
        groupEntity.setExpand(true);
        notifyDataSetChanged();
    }

    /**
     * 收缩
     *
     * @param position
     * @return
     */
    public void collapse(int position, ContactsPeopleEntity groupEntity) {
        int subItemCount = groupEntity.getList().size();
        for (int i = 0; i < subItemCount; i++) {
            mData.remove(position + 1);
        }
        groupEntity.setExpand(false);
        notifyDataSetChanged();
    }
}
